import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:pointycastle/digests/sha256.dart';
import 'package:pointycastle/key_derivators/pbkdf2.dart';
import 'package:pointycastle/key_derivators/api.dart';
import 'package:pointycastle/macs/hmac.dart';
import 'package:pointycastle/ecc/api.dart';
import 'package:pointycastle/ecc/curves/secp256k1.dart';
import 'package:hex/hex.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/random/fortuna_random.dart';
import 'package:pointycastle/key_generators/api.dart';
import 'package:convert/convert.dart';
import '/utils/ECCSecp256k1.dart';

class EncryptLogic extends GetxController {
  final result = ''.obs;
  final plainTextController = TextEditingController(); //明文
  final KeyController = TextEditingController(); //密钥
  final ivText = TextEditingController(); //初始化向量IV


  void encryptAes() async {
    try {
      final plainTextBytesList = hex.decode(plainTextController.text);

      Uint8List encryptKey = Uint8List.fromList(hex.decode(KeyController.text));
      String ivHex = ivText.text;
      Uint8List ivBytes = Uint8List.fromList(hex.decode(ivHex));
      encrypt.IV iv = encrypt.IV(ivBytes);

      // ✅ 正确构造 Key
      final keyObj = encrypt.Key(encryptKey);
      final encrypter = encrypt.Encrypter(
          encrypt.AES(keyObj, mode: encrypt.AESMode.cbc));
      final encrypted = encrypter.encryptBytes(plainTextBytesList, iv: iv);


      result.value = '''
    加密结果:
    hex: ${hex.encode(encrypted.bytes)} \n
    base64: ${encrypted.base64}
    ''';
    } catch (e) {
      result.value = '加密数据失败：${e.toString()}';
    } finally {
      EasyLoading.dismiss();
    }
    print(result.value);
  }

  void encryptEcc() async {
    try {
      final encrypted = ECIESUtil.encrypt( plainTextController.text,  KeyController.text);
      result.value = '''
    加密结果:
    hex: ${hex.encode(encrypted)} \n
    base64: ${base64Encode(encrypted)}
    ''';
    } catch (e) {
      result.value = '加密数据失败：${e.toString()}';
    } finally {
      EasyLoading.dismiss();
    }
    print(result.value);
  }


}


